
/*
 * mutex.h
 *
 *  Created on: May 27, 2013
 *      Author: Aden
 */

#ifndef MUTEX_H_
#define MUTEX_H_

#include "queue.h"
#include <pthread.h>

//this construction is to remove the reliance on pcb.h from mutex.h and condition_variable.h,
//thus removing a cyclical dependency
#ifndef PCB_STR_
#define PCB_STR_
typedef struct pcb_str PCBStr;
typedef PCBStr * PCBPtr;
#endif

typedef struct mutex_str {
  pthread_mutex_t atomic;// = PTHREAD_MUTEX_INITIALIZER; //lock to ensure atomicity
  PCBPtr locked;// = 0; //the current locking process; 0 indicates none
  QueuePtr queue;

  //Member functions
  char*(*lock)(struct mutex_str *, PCBPtr);
  char*(*unlock)(struct mutex_str *, PCBPtr);

} Mutex;

//initializes a new mutex
char* mutex_init(Mutex* this);
//locks the mutex. after call, locking process will have PCBPtr in this->locked
char* mutex_lock(Mutex* this, PCBPtr process);
//unlocks the mutex. after call, locking process will have PCBPtr in this->locked
char* mutex_unlock(Mutex* this, PCBPtr process);

#endif /* MUTEX_H_ */
